package cn.qingyun.gis.modules.init.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.qingyun.gis.modules.init.system.entity.SysRoleState;
import cn.qingyun.gis.modules.init.system.mapper.SysRoleStateMapper;
import cn.qingyun.gis.modules.init.system.request.RoleBindSteteRequest;
import cn.qingyun.gis.modules.init.system.service.ISysRoleStateService;
import cn.qingyun.gis.modules.init.system.vo.SysRoleVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色绑定流程状态 服务实现类
 * </p>
 *
 * @author author
 * @since 2023-06-08
 */
@Service
public class SysRoleStateServiceImpl extends ServiceImpl<SysRoleStateMapper, SysRoleState> implements ISysRoleStateService {

    @Override
    public void bind(RoleBindSteteRequest roleBindSteteRequest) {
        QueryWrapper<SysRoleState> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysRoleState::getRoleId, roleBindSteteRequest.getRoleId());

        this.remove(queryWrapper);

        List<SysRoleState> roleStateList = Lists.newArrayList();
        for (Integer procStatus : roleBindSteteRequest.getProcStatuses()) {
            SysRoleState roleState = new SysRoleState();

            roleState.setRoleId(roleBindSteteRequest.getRoleId());
            roleState.setProcStatus(procStatus);

            roleStateList.add(roleState);
        }

        this.saveBatch(roleStateList);
    }

    @Override
    public void fillBindStateInfo(List<SysRoleVo> records) {
        if (CollUtil.isNotEmpty(records)) {
            Set<String> roleIds = records.stream().map(SysRoleVo::getId).collect(Collectors.toSet());
            QueryWrapper<SysRoleState> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().in(SysRoleState::getRoleId, roleIds);

            List<SysRoleState> roleStates = this.list(queryWrapper);

            Map<String, List<SysRoleState>> roleStateGroup = roleStates.stream().collect(Collectors.groupingBy(SysRoleState::getRoleId));

            for (SysRoleVo record : records) {
                List<SysRoleState> sysRoleStates = roleStateGroup.get(record.getId());
                if (CollUtil.isNotEmpty(sysRoleStates)) {
                    record.setProcStatuses(sysRoleStates.stream().map(SysRoleState::getProcStatus).collect(Collectors.toList()));
                } else {
                    record.setProcStatuses(Lists.newArrayList());
                }

            }
        }
    }
}
